package com.tmc.service.intair;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.bean.common.Pagination;
import com.tmc.bean.intair.EthBookingReq;
import com.tmc.bean.intair.EthFare;
import com.tmc.bean.intair.EthOrder;
import com.tmc.bean.intair.IntairShoppingReq;
import com.tmc.entity.intair.IntairOrder;
import com.tmc.service.cache.CacheServiceImpl;
import com.tmc.util.IntairFareUtil;
import com.tmc.util.ObjectUtil;

@Service
public class IntairCoreServiceImpl {
	
	@Autowired
	private EthShoppingServiceImpl shoppingService;
	
	@Autowired
	private EthPricingServiceImpl pricingService;
	
	@Autowired
	private EthBookingServiceImpl bookingService;
	
	@Autowired
	private IntairOrderServiceImpl orderService;
	
	@Autowired
	private CacheServiceImpl cache;

	@SuppressWarnings("unchecked")
	public List<EthFare> shopping(ContextInfo context, IntairShoppingReq req){
		CommonResult cr = shoppingService.search(context, JSON.toJSONString(req), req.getVendorCode());
		return (List<EthFare>) IntairFareUtil.buildShoppingResponse(cr.toJson()).getObj();
	}
	
	public String getShoppingCfg(ContextInfo context){
		return "IBE";
	}

	public CommonResult pricing(ContextInfo context, String fareKey) {
		CommonResult cr = pricingService.pricing(context, fareKey);
		if (cr.isSuccess()){
			EthFare fare = JSON.parseObject(JSON.toJSONString(cr.getObj()), EthFare.class);
			IntairFareUtil.setExtInfo(fare);
			cache.put(context.getToken() + "_pricingFareKey", fare);
		}
		return cr;
	}
	
	public EthFare getPricingFare(ContextInfo context){
		return (EthFare) cache.get(context.getToken() + "_pricingFareKey");
	}

	public CommonResult booking(ContextInfo context, EthBookingReq req) {
		CommonResult cr = bookingService.booking(context, req);
		return cr;
	}
	
	private String getCacheKey (ContextInfo context) {
		return "current_order_" + context.getToken();
	}

	public EthOrder getCurrentOrder(ContextInfo context) {
		String key = this.getCacheKey(context);
		EthOrder cacheOrder = (EthOrder) cache.get(key);
		if (cacheOrder != null) {
			return cacheOrder;
		}
		Map<String, String> params = new HashMap<String, String>();
		params.put("token", context.getToken());
		IntairOrder order = orderService.getCurrent(context);
		EthOrder result = ObjectUtil.makeTargetBean(order, EthOrder.class);
		return result;
	}
	
	public Pagination<IntairOrder> findMyOrders(ContextInfo context){
		IntairOrder cond = new IntairOrder();
		Pagination<IntairOrder> page = orderService.findByCon(context, cond, 1, 10);
		return page;
	}
}
